//
//  GlobalMethod+Device.swift
//  全局方法 - 设备相关
//
//  Created by mini on 2025/4/28.
//

import AdSupport
import AppTrackingTransparency
import AVFoundation
import Contacts
import CoreLocation
import CoreTelephony
import Foundation
import Photos
import SystemConfiguration
import SystemConfiguration.CaptiveNetwork
import Darwin

extension GlobalMethod {

    // MARK: - 获取APP名称
    static func getAppName() -> String? {
        guard let infoDictionary = Bundle.main.infoDictionary else {
            return nil
        }
        return infoDictionary["CFBundleDisplayName"] as? String
    }

    // MARK: - 获取APP包名
    static func getBundleName() -> String? {
        guard let infoDictionary = Bundle.main.infoDictionary else {
            return nil
        }
        return infoDictionary["CFBundleName"] as? String
    }

    // MARK: - 获取APP版本号
    static var getVersion: String? {
        return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    }

    // MARK: - 获取APP构建号
    static var getBuildVersion: String? {
        return Bundle.main.infoDictionary?["CFBundleVersion"] as? String
    }

    // MARK: - 获取设备mac ：取wifi里的bssid
    static func getMacBSSID() -> String? {
        if let interfaces = CNCopySupportedInterfaces() as? [String] {
            for interface in interfaces {
                if let info = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: AnyObject],
                   let bssid = info["BSSID"] as? String
                {
                    return bssid
                }
            }
        }
        return nil
    }

    static func getCurrentSSID() -> String {
        var wifiName = ""
        if let interfaces = CNCopySupportedInterfaces() as? [String] {
            for interface in interfaces {
                if let dictRef = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: Any],
                   let ssid = dictRef[kCNNetworkInfoKeySSID as String] as? String
                {
                    wifiName = ssid
                    break
                }
            }
        }
        return wifiName
    }

    // MARK: - 判断网络连接-是否使用代理
    static func isUsingProxy(for urlString: String = "https://www.apple.com") -> Bool {
        guard let url = URL(string: urlString) else { return false }
        guard let proxySettings = CFNetworkCopySystemProxySettings()?.takeUnretainedValue() as? [String: Any],
              let proxies = CFNetworkCopyProxiesForURL(url as CFURL, proxySettings as CFDictionary)
              .takeUnretainedValue() as? [[String: Any]],
              let settings = proxies.first,
              let proxyType = settings[kCFProxyTypeKey as String] as? String
        else {
            return false
        }
        let proxyTypes = [
            kCFProxyTypeAutoConfigurationURL as String,
            kCFProxyTypeAutoConfigurationJavaScript as String,
            kCFProxyTypeHTTP as String,
            kCFProxyTypeHTTPS as String,
            kCFProxyTypeSOCKS as String,
        ]
        return proxyTypes.contains(proxyType)
    }

    // MARK: - 获取设备网络类型  2G/3G/4G/5G/WIFI/OTHER
    static func getNetworkType() -> String {
        let notReachable = "none"

        // 创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
        var zeroAddress = sockaddr()
        bzero(&zeroAddress, MemoryLayout<sockaddr>.size)
        zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
        zeroAddress.sa_family = sa_family_t(AF_INET)

        // Recover reachability flags
        guard let defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else {
            return notReachable
        }

        var flags: SCNetworkReachabilityFlags = []
        // 获得连接的标志
        let didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags)

        // 如果不能获取连接标志，则不能连接网络，直接返回
        if !didRetrieveFlags {
            return notReachable
        }

        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)

        if isReachable && !needsConnection {
            // 继续执行
        } else {
            return notReachable
        }

        if flags.contains(.connectionRequired) {
            return notReachable
        } else if flags.contains(.isWWAN) {
            let info = CTTelephonyNetworkInfo()
            var currentRadioAccessTechnology: String?

            if #available(iOS 12.1, *) {
                if let radioDic = info.serviceCurrentRadioAccessTechnology,
                   !radioDic.keys.isEmpty
                {
                    currentRadioAccessTechnology = radioDic[radioDic.keys.first!]
                } else {
                    return notReachable
                }
            } else {
                currentRadioAccessTechnology = info.currentRadioAccessTechnology
            }

            if let currentRadioAccessTechnology = currentRadioAccessTechnology {
                if #available(iOS 14.1, *) {
                    if currentRadioAccessTechnology == CTRadioAccessTechnologyNRNSA ||
                        currentRadioAccessTechnology == CTRadioAccessTechnologyNR
                    {
                        return "5G"
                    }
                }

                if currentRadioAccessTechnology == CTRadioAccessTechnologyLTE {
                    return "4G"
                } else if [CTRadioAccessTechnologyWCDMA,
                           CTRadioAccessTechnologyHSDPA,
                           CTRadioAccessTechnologyHSUPA,
                           CTRadioAccessTechnologyCDMAEVDORev0,
                           CTRadioAccessTechnologyCDMAEVDORevA,
                           CTRadioAccessTechnologyCDMAEVDORevB,
                           CTRadioAccessTechnologyeHRPD].contains(currentRadioAccessTechnology)
                {
                    return "3G"
                } else if [CTRadioAccessTechnologyEdge,
                           CTRadioAccessTechnologyGPRS,
                           CTRadioAccessTechnologyCDMA1x].contains(currentRadioAccessTechnology)
                {
                    return "2G"
                } else {
                    return "other"
                }
            } else {
                return notReachable
            }
        } else {
            return "wifi"
        }
    }

    // MARK: - 判断网络连接-是否使用vpn
    static func isVPNConnected() -> Bool {
        guard let proxySettings = CFNetworkCopySystemProxySettings()?.takeUnretainedValue() as? [String: Any],
              let scoped = proxySettings["__SCOPED__"] as? [String: Any]
        else {
            return false
        }
        for key in scoped.keys {
            if key.contains("tap") || key.contains("tun") || key.contains("ppp") {
                // print(">>>>>> 开启了 VPN")
                return true
            }
        }
        // print(">>>>>> 没有开启 VPN")
        return false
    }

    // MARK: - 判断设备是否越狱
    static func isDeviceJailbroken() -> Bool {
        return isJailbrokenByFileCheck()
            || isJailbrokenBySandboxCheck()
            || isJailbrokenByDylibCheck()
            || isJailbrokenByURLSchemeCheck()
            || isJailbrokenByEnvironmentCheck()
    }

    // 1. 文件路径检查
    static func isJailbrokenByFileCheck() -> Bool {
        let jailbreakPaths = [
            "/Applications/Cydia.app",
            "/Library/MobileSubstrate/MobileSubstrate.dylib",
            "/bin/bash",
            "/usr/sbin/sshd",
            "/etc/apt",
            "/private/var/lib/apt/",
            "/var/lib/cydia",
            "/var/cache/apt",
            "/var/lib/undecimus/",
            "/var/containers/Bundle/iosbinpack64/",
            "/var/containers/Bundle/dylibs/",
        ]
        for path in jailbreakPaths {
            if FileManager.default.fileExists(atPath: path) {
                return true
            }
        }
        return false
    }

    // 2. 沙盒越权写入检查
    static func isJailbrokenBySandboxCheck() -> Bool {
        let testPath = "/private/jailbreak_test.txt"
        if FileManager.default.fileExists(atPath: testPath) {
            return true
        }
        do {
            try "test".write(toFile: testPath, atomically: true, encoding: .utf8)
            try FileManager.default.removeItem(atPath: testPath)
            return true
        } catch {
            return false
        }
    }

    // 3. 动态库注入检查
    static func isJailbrokenByDylibCheck() -> Bool {
        let path = "/Library/MobileSubstrate/MobileSubstrate.dylib"
        let handle = dlopen(path, RTLD_NOW)
        if handle != nil {
            dlclose(handle)
            return true
        }
        return false
    }

    // 4. URL Scheme 检查（需要在 Info.plist 中配置白名单）
    static func isJailbrokenByURLSchemeCheck() -> Bool {
        if let url = URL(string: "cydia://"), UIApplication.shared.canOpenURL(url) {
            return true
        }
        return false
    }

    // 5. 环境变量注入检查
    static func isJailbrokenByEnvironmentCheck() -> Bool {
        return getenv("DYLD_INSERT_LIBRARIES") != nil
    }

    // MARK: - 获取设备开机到现在的毫秒数 *1000 - (包含睡眠时间)
    static func millisecondsSinceBootIncludingSleep() -> UInt64 {
        let uptime = mach_absolute_time()
        var timebase = mach_timebase_info_data_t()
        mach_timebase_info(&timebase)
        var uptimeMilliseconds = uptime * UInt64(timebase.numer)
        uptimeMilliseconds /= UInt64(timebase.denom)
        uptimeMilliseconds /= 1_000_000
        return uptimeMilliseconds
    }

    // MARK: - 获取屏幕尺寸  iPhone 12  6.1英寸
    static func getScreenDiagonalSize() -> String {
        let screenBounds = UIScreen.main.bounds
        let scale = UIScreen.main.scale
        let ppi: CGFloat = 460 // iPhone 12 的 PPI 为 460
        let width = screenBounds.size.width * scale
        let height = screenBounds.size.height * scale
        let diagonalPixels = sqrt(pow(width, 2) + pow(height, 2))
        let diagonalInches = diagonalPixels / ppi
        print("屏幕对角线尺寸: \(String(format: "%.2f", diagonalInches)) 英寸")
        return String(format: "%.2f", diagonalInches)
    }

    // MARK: - 获取IDFA
    static func getIDFA() {
        // 追踪权限
        var idfa = GlobalMethod.readUnprefixedStrFromUserDefaults(forKey: LOCAL_IDFA)
        let adidRange = idfa.range(of: "0000-0000-0000")
        if adidRange != nil {
            // 不是想要的格式
            idfa = ""
        }
        if isStr(idfa) {
            GlobalMethod.writeUnprefixedStr(idfa, forKey: LOCAL_IDFA)
        } else {
            let advertisingIdentifier = GlobalMethod.getAdvertisingIdentifier()
            GlobalMethod.writeUnprefixedStr(advertisingIdentifier, forKey: LOCAL_IDFA)
        }
    }

    static func getAdvertisingIdentifier() -> String {
        var advertisingIdentifier = ""
        let semaphore = DispatchSemaphore(value: 0)

        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                switch status {
                case .authorized:
                    print("用户允许广告追踪")
                    advertisingIdentifier = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                case .denied, .restricted:
                    print("用户拒绝广告追踪")
                    advertisingIdentifier = ""
                case .notDetermined:
                    // 不会执行到这里，因为弹窗只会返回允许或拒绝
                    break
                @unknown default:
                    break
                }
                // 处理授权状态的代码
                semaphore.signal()
            }
        }
        semaphore.wait()
        return advertisingIdentifier
    }

    // MARK: - 获取设备的原始型号
    static func getDeviceModel() -> String? {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        return identifier
    }

    // MARK: - 获取设备名称
    static var getDeviceName: String? {
        return mapToDevice(identifier: GlobalMethod.getDeviceModel() ?? "")
    }

    static func mapToDevice(identifier: String) -> String {
        switch identifier {
        // iPhone 16 系列
        case "iPhone17,1": return "iPhone 16"
        case "iPhone17,2": return "iPhone 16 Plus"
        case "iPhone17,3": return "iPhone 16 Pro"
        case "iPhone17,4": return "iPhone 16 Pro Max"
        // iPhone 15 系列
        case "iPhone15,4": return "iPhone 15"
        case "iPhone15,5": return "iPhone 15 Plus"
        case "iPhone16,1": return "iPhone 15 Pro"
        case "iPhone16,2": return "iPhone 15 Pro Max"
        // iPhone 14 系列
        case "iPhone14,7": return "iPhone 14"
        case "iPhone14,8": return "iPhone 14 Plus"
        case "iPhone15,2": return "iPhone 14 Pro"
        case "iPhone15,3": return "iPhone 14 Pro Max"
        // iPhone 13 系列
        case "iPhone14,4": return "iPhone 13 mini"
        case "iPhone14,5": return "iPhone 13"
        case "iPhone14,2": return "iPhone 13 Pro"
        case "iPhone14,3": return "iPhone 13 Pro Max"
        // iPhone 12 系列
        case "iPhone13,1": return "iPhone 12 mini"
        case "iPhone13,2": return "iPhone 12"
        case "iPhone13,3": return "iPhone 12 Pro"
        case "iPhone13,4": return "iPhone 12 Pro Max"
        // iPhone 11 系列
        case "iPhone12,1": return "iPhone 11"
        case "iPhone12,3": return "iPhone 11 Pro"
        case "iPhone12,5": return "iPhone 11 Pro Max"
        // iPhone X 系列
        case "iPhone10,3": return "iPhone X"
        case "iPhone10,6": return "iPhone X"
        case "iPhone11,2": return "iPhone XS"
        case "iPhone11,4": return "iPhone XS Max"
        case "iPhone11,6": return "iPhone XS Max"
        case "iPhone11,8": return "iPhone XR"
        // iPhone 8 系列
        case "iPhone10,1": return "iPhone 8"
        case "iPhone10,4": return "iPhone 8"
        case "iPhone10,2": return "iPhone 8 Plus"
        case "iPhone10,5": return "iPhone 8 Plus"
        // iPhone 7 系列
        case "iPhone9,1": return "iPhone 7"
        case "iPhone9,3": return "iPhone 7"
        case "iPhone9,2": return "iPhone 7 Plus"
        case "iPhone9,4": return "iPhone 7 Plus"
        // iPhone 6 系列
        case "iPhone7,2": return "iPhone 6"
        case "iPhone7,1": return "iPhone 6 Plus"
        case "iPhone8,1": return "iPhone 6s"
        case "iPhone8,2": return "iPhone 6s Plus"
        case "iPhone8,4": return "iPhone SE"
        // iPhone SE 系列
        case "iPhone12,8": return "iPhone SE"
        case "iPhone14,6": return "iPhone SE"
        default: return identifier
        }
    }

    // MARK: - 是否开启定位权限
    static func isOnLocationAuthorization() -> Bool {
        let status = CLLocationManager().authorizationStatus
        switch status {
        case .notDetermined, .restricted, .denied:
            return false
        case .authorizedAlways, .authorizedWhenInUse:
            return true
        @unknown default:
            return false
        }
    }

    // MARK: - 获取IP地址
    static func getIPAddress() -> String {
        var address = "error"
        var ifaddr: UnsafeMutablePointer<ifaddrs>?
        guard getifaddrs(&ifaddr) == 0 else {
            return address
        }
        defer {
            freeifaddrs(ifaddr)
        }
        var ptr = ifaddr
        while ptr != nil {
            defer { ptr = ptr?.pointee.ifa_next }
            guard let interface = ptr?.pointee else { continue }
            let addrFamily = interface.ifa_addr.pointee.sa_family

            if addrFamily == UInt8(AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                let name = String(cString: interface.ifa_name)
                if name == "en0" {
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(interface.ifa_addr,
                                socklen_t(interface.ifa_addr.pointee.sa_len),
                                &hostname,
                                socklen_t(hostname.count),
                                nil,
                                0,
                                NI_NUMERICHOST)
                    address = String(cString: hostname)
                }
            }
        }

        return address
    }

    // MARK: - 获取当前时间
    static func getCurrentTime(dateFormat: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        let currentDate = Date()
        let formattedDate = dateFormatter.string(from: currentDate)
        return formattedDate
    }

    // MARK: - 开启/关闭手电
    static func toggleFlashlight() {
        if let device = AVCaptureDevice.default(for: .video), device.hasTorch {
            do {
                try device.lockForConfiguration()
                if device.torchMode == .off {
                    try device.setTorchModeOn(level: 1.0)
                } else {
                    device.torchMode = .off
                }
                device.unlockForConfiguration()
            } catch {
                print("切换手电筒失败: \(error)")
            }
        }
    }

    // MARK: - 检查是否已开启 相机权限
    static func isOpenCameraPermissions(completion: @escaping (Bool) -> Void) {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        switch status {
        case .notDetermined:
            // 尚未选择，发起请求
            AVCaptureDevice.requestAccess(for: .video) { granted in
                if granted == false {
                    // 用户拒绝
                    GlobalMethod.mainQueueBlock {
                        let view = PermissionsAlertView()
                        view.resetView(model: ModelBtn(title: "Permissions", content: DESC_POWER_CAMERA, leftTitle: "Stop", rightTitle: "Turning On"))
                        view.blockRightClick = {
                            if let url = URL(string: UIApplication.openSettingsURLString),
                               UIApplication.shared.canOpenURL(url)
                            {
                                UIApplication.shared.open(url, options: [:], completionHandler: nil)
                            }
                        }
                        view.show()
                    }
                }
                completion(granted)
            }
        case .restricted, .denied:
            // 由于家长控制等限制 / 用户已拒绝访问相机
            let view = PermissionsAlertView()
            view.resetView(model: ModelBtn(title: "Permissions", content: DESC_POWER_CAMERA, leftTitle: "Stop", rightTitle: "Turning On"))
            view.blockRightClick = {
                if let url = URL(string: UIApplication.openSettingsURLString),
                   UIApplication.shared.canOpenURL(url)
                {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
            view.show()
            completion(false)
        case .authorized:
            // 相机权限已经被授权
            completion(true)
        @unknown default:
            completion(false)
        }
    }

    // MARK: - 检查是否已开启 相册权限
    static func isOpenAlbumPermissions(completion: @escaping (Bool) -> Void) {
        let status = PHPhotoLibrary.authorizationStatus()
        switch status {
        case .authorized, .limited:
            // 用户已授权，可以打开相册
            completion(true)
        case .denied, .restricted:
            // 用户未授权，提醒用户去设置页面开启权限
            let view = PermissionsAlertView()
            view.resetView(model: ModelBtn(title: "Permissions", content: DESC_POWER_PHOTOALBUM, leftTitle: "Stop", rightTitle: "Turning On"))
            view.blockRightClick = {
                if let url = URL(string: UIApplication.openSettingsURLString),
                   UIApplication.shared.canOpenURL(url)
                {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
            view.show()
            completion(false)
        case .notDetermined:
            // 请求权限
            PHPhotoLibrary.requestAuthorization { status in
                DispatchQueue.main.async {
                    if status == .authorized || status == .limited {
                        // 用户授权了，可以打开相册
                        completion(true)
                    } else {
                        // 用户拒绝了权限
                        completion(false)
                    }
                }
            }
        @unknown default:
            completion(false)
        }
    }

    // MARK: - 检查联系人权限
    static func isOpenContactPermissions(completion: @escaping (Bool) -> Void) {
        let status = CNContactStore.authorizationStatus(for: .contacts)
        switch status {
        case .authorized:
            // 已授权：直接返回true
            completion(true)
//        case .limited:
//            // iOS 18.0新增：部分授权-受限制的权限 （弹窗）
//            completion(false)
        case .denied, .restricted, .limited:
            // 已拒绝或受限：提示用户去设置中开启权限
            let view = PermissionsAlertView()
            view.resetView(model: ModelBtn(title: "Permissions", content: DESC_ADDRESS_BOOK, leftTitle: "Stop", rightTitle: "Turning On"))
            view.blockRightClick = {
                if let url = URL(string: UIApplication.openSettingsURLString),
                   UIApplication.shared.canOpenURL(url)
                {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                }
            }
            view.show()
            completion(false)
        case .notDetermined:
            // 未决定：需要先请求权限
            let store = CNContactStore()
            store.requestAccess(for: .contacts) { granted, _ in
                DispatchQueue.main.async {
                    self.isOpenContactPermissions(completion: completion)
//                    if granted {
//                        // 用户授权了，可以访问联系人
//                        completion(true)
//                    } else {
//                        // 用户拒绝了权限
//                        let view = PermissionsAlertView()
//                        view.resetView(model: ModelBtn(title: "Permissions", content: DESC_ADDRESS_BOOK, leftTitle: "Stop", rightTitle: "Turning On"))
//                        view.blockRightClick = {
//                            if let url = URL(string: UIApplication.openSettingsURLString),
//                               UIApplication.shared.canOpenURL(url)
//                            {
//                                UIApplication.shared.open(url, options: [:], completionHandler: nil)
//                            }
//                        }
//                        view.show()
//                        completion(false)
//                    }
                }
            }
        @unknown default:
            completion(false)
        }
    }

    // MARK: - 获取通讯录信息
    static func getAddressBookArray(completion: @escaping ([[String: String]]) -> Void) {
        var addressBookArray: [[String: String]] = []

        // 1.获取授权状态
        let status = CNContactStore.authorizationStatus(for: .contacts)

        // 2.如果是未决定,请求授权
        if status == .notDetermined {
            let store = CNContactStore()
            store.requestAccess(for: .contacts) { granted, _ in
                if granted {
                    print("授权成功")
                }
            }
        }

        // GlobalMethod.userBehaviorRecord(pageName: "ExtInfoUpload", action: "Contact_Fetch", extInfo: nil)

        // 3.获取联系人
        // 3.1.创建联系人仓库
        let store = CNContactStore()
        // 3.2.创建联系人的请求对象
        // keys决定这次要获取哪些信息,比如姓名/电话
        let fetchKeys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
        let request = CNContactFetchRequest(keysToFetch: fetchKeys as [CNKeyDescriptor])

        GlobalMethod.asyncBlock {
            // 3.3.请求联系人
            do {
                try store.enumerateContacts(with: request) { contact, _ in
                    // 1.获取姓名
                    let firstname = contact.givenName
                    let lastname = contact.familyName

                    // 2.获取电话号码
                    let phones = contact.phoneNumbers

                    // 3.遍历电话号码
                    if isAry(phones) {
                        // 存了手机号
                        var phoneNumbers: [String] = []
                        for labelValue in phones {
                            let phoneNumber = labelValue.value
                            phoneNumbers.append(phoneNumber.stringValue)
                        }
                        let allPhones = phoneNumbers.joined(separator: ",")
                        addressBookArray.append([
                            // 姓名
                            "cautiously": "\(firstname)\(isStr(firstname) && isStr(lastname) ? " " : "")\(lastname)",
                            "waked": allPhones, // 手机号
                        ])
                    } else {
                        // 没存手机号码，只存了姓名
                        addressBookArray.append([
                            // 姓名
                            "cautiously": "\(firstname)\(isStr(firstname) && isStr(lastname) ? " " : "")\(lastname)",
                            "waked": "", // 手机号
                        ])
                    }
                }

                completion(addressBookArray)
            } catch {
                print("获取通讯录失败: \(error)")
                completion([])
            }
        }
    }

    // MARK: -  存储相关
    // 未使用存储大小 - 格式化的，返回"1.5 GB" 或 "750 MB"
    static func getNewFreeSize() -> String {
        do {
            let url = URL(fileURLWithPath: NSTemporaryDirectory())
            let dicts = try url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
            if let freeSize = dicts.volumeAvailableCapacityForImportantUsage {
                // 格式化输出，转换为更易读的形式
                let formatter = ByteCountFormatter()
                formatter.allowedUnits = [.useGB, .useMB]
                formatter.countStyle = .file
                return formatter.string(fromByteCount: freeSize)
            }
        } catch {
            print("获取可用空间失败: \(error)")
        }
        return "0"
    }
    // 未使用存储大小 - 未格式化（字节）
    static func getNewFreeSizeWithByte() -> Int64 {
        do {
            let url = URL(fileURLWithPath: NSTemporaryDirectory())
            let dicts = try url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
            if let freeSize = dicts.volumeAvailableCapacityForImportantUsage {
                return freeSize
            }
        } catch {
            print("获取可用空间失败: \(error)")
        }
        return 0
    }

    // 总存储大小
    static func totalDiskSpaceInBytes() -> Int64 {
        do {
            let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
            if let space = systemAttributes[.systemSize] as? Int64 {
                return space
            }
        } catch {
            print("获取总空间失败: \(error)")
        }
        return 0
    }

    // 总内存大小

    // 未使用内存大小 - 当前可用内存
    static func getAvailableMemorySize() -> Int64 {
        // 定义 HOST_VM_INFO_COUNT 常量
        let HOST_VM_INFO_COUNT: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout<vm_statistics_data_t>.size / MemoryLayout<integer_t>.size)
        
        var datastats = vm_statistics_data_t()
        var count = HOST_VM_INFO_COUNT
        
        // 获取主机
        let host = mach_host_self()
        
        // 获取统计信息
        let kernReturn = withUnsafeMutablePointer(to: &datastats) { pointer in
            pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { pointer in
                host_statistics(host, HOST_VM_INFO, pointer, &count)
            }
        }
        
        if kernReturn != KERN_SUCCESS {
            return 0
        }
        
        // 计算可用内存
        let freeMemory = UInt64(vm_page_size) * UInt64(datastats.free_count)
        let inactiveMemory = UInt64(vm_page_size) * UInt64(datastats.inactive_count)
        let totalAvailableMemory = Int64(freeMemory + inactiveMemory)
        
        return totalAvailableMemory
    }
}
